import React, { Component } from 'react';
import { Table } from 'antd';
import { connect } from 'dva';
import getPagination from '../pagination';

@connect(state => state)
export default class DetailTable extends Component {


  componentWillMount() {
    this.getList();
  }

  getList = () => {
    const { dispatch, namespace, tableType, payload } = this.props;
    dispatch({
      type: `${namespace}/${tableType}_query`,
      payload: {
        size: 10,
        current: 1,
        query: payload,
      },
    });
  }

  pageChange = (page, size) => {
    const { dispatch, namespace, tableType } = this.props;
    dispatch({
      type: `${namespace}/${tableType}_query`,
      payload: {
        page,
      }
    });
  }

  selectedKeysChange = (keys) => {
    const { dispatch, namespace, tableType } = this.props;
    dispatch({
      type: `${namespace}/updateState`,
      payload: {
        [`${tableType}_selectedRowKeys`]: keys,
      }
    });
  }

  onShowSizeChange = (page, size) => {
    const { dispatch, namespace, tableType } = this.props;
    dispatch({
      type: `${namespace}/${tableType}_query`,
      payload: {
        size,
      }
    });
  }

  render() {
    /**
     * @prop showSelection: 是否显示rowSelection
     * @prop pagination: pagination有父级组件提供
     * @prop namespace: model的namespace
     * @prop tableType: 在一个model中有多个table的话,用这个tableType来区分
     */
    const { namespace, tableType, columns, pagination = false, showSelection = false } = this.props;
    const currState = this.props[namespace];
    const currPagiantion = currState[`${tableType}_pagination`];
    const { current, size } = currPagiantion;
    const rowSelection = {
      selectedRowKeys: currState[`${tableType}_selectedRowKeys`],
      onChange: this.selectedKeysChange,
    };
    return (
      <Table
        columns={columns}
        rowSelection={showSelection ? rowSelection : null}
        dataSource={currState[`${tableType}_list`]}
        pagination={pagination || getPagination({
          pageSize: current,
          size,
          onChange: this.pageChange, // 页码改变的回调，参数是改变后的页码及每页条数
          onShowSizeChange: this.onShowSizeChange // pageSize 变化的回调
        })}
      />
    );
  }
}

